package time_task

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

//每隔5分钟从onlinedetail表里统计在线用户，然后写到表onlinecount里
func UserOnlineCount() error {
	//在线玩家数
	sqlOnline := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v

	`, TableOnlineDetail)
	//roomid非零时表示用户在一个房间里玩,即表示在玩
	sqlOnlinePlay := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			roomid != 0

	`, TableOnlineDetail)
	var countOnline, countOnlinePlay int64
	o := orm.NewOrm()
	err := o.Raw(sqlOnline).QueryRow(&countOnline)
	if err != nil {
		return err
	}
	err = o.Raw(sqlOnlinePlay).QueryRow(&countOnlinePlay)
	if err != nil {
		return err
	}

	insertData := map[string]interface{}{
		"ctime":  time.Now().Unix(),
		"online": countOnline,     //在线玩家数
		"play":   countOnlinePlay, //在玩游戏的玩家数
	}
	values, sql := InsertSql(TableOnlineCount, insertData)
	_, err = o.Raw(sql, values).Exec()
	if err != nil {
		return err
	}
	return nil
}

//每隔30分钟从onlinedetail表里统计在线用户，然后写到表onlinecount里
func RegisterUserCount() error {
	//30分钟内注册的新玩家数
	now := time.Now().Unix()
	sqlRegister := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			operate_type = %v AND create_time >= %v AND create_time < %v
	`, TableSystemUserTran, SysOpRegister, now-30*60, now)

	var count int64
	o := NewDBOrm(DBChessLog)
	err := o.Raw(sqlRegister).QueryRow(&count)
	if err != nil {
		return err
	}

	insertData := map[string]interface{}{
		"count":       count,
		"create_time": now,
	}
	values, sql := InsertSql(TableRegisterCount, insertData)
	_, err = o.Raw(sql, values).Exec()
	if err != nil {
		return err
	}
	return nil
}
